package com.edu.hre.struts.action.pim;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.LabelValueBean;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmpJobs;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmpJobUpdateForm;

public class EmpJobUpdateAction extends DispatchAction{
	
	private static final Logger logger = Logger.getLogger(EmpJobUpdateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "empJobUpdate";
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());

		EmpJobUpdateForm beanForm = (EmpJobUpdateForm) form;
		beanForm.setIsAddNew(true);

		if(request.getParameter(StringConstants.BTN_ADD) == null){
			
			int empNum = CommonUtils.getIntParameter("emp_num", request);
			beanForm.setEmpNumber(empNum);

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);

		String message = validateForm(beanForm, true);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			beanForm.setSuccess(false);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		Date startDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getStartDate()));
		Date endDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getEndDate()));
		FormFile myFile = beanForm.getContractFile();
		
		HreEmpJobs tmp = new HreEmpJobs();
		tmp.setEmpNumber(beanForm.getEmpNumber());
		
		tmp.setJobTitleId(beanForm.getJobTitle());
		tmp.setEmpStatusId(beanForm.getEmpStatus());
		tmp.setJobCategoryId(beanForm.getJobCategory());
		tmp.setJoinedDate(CommonUtils.stringToDate(beanForm.getJoinedDate()));
		tmp.setSubUnitId(beanForm.getSubUnit());
		tmp.setLocationId(beanForm.getLocation());
		tmp.setContractStartDate(startDate);
		tmp.setContractEndDate(endDate);
		tmp.setTerminatedStatus(false);
		
		if(myFile != null && StringUtils.isNotBlank(myFile.getFileName())){

			tmp.setContractFileType(myFile.getContentType());
			tmp.setContractFileSize(myFile.getFileSize());
			tmp.setContractFileName(myFile.getFileName());
			tmp.setContractFileContent(myFile.getFileData());
		}

		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.INSERT_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		HreEmployee emp = baseService.getFirstPojo("empNumber", Compare.EQUAL, tmp.getEmpNumber(), null, null, 0, HreEmployee.class);
		emp.setWorkStation(tmp.getSubUnitId());
		emp.setJobTitleCode(beanForm.getJobTitle());
		emp.setEmpStatus(beanForm.getEmpStatus());
		baseService.saveOrUpdate(emp);

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		EmpJobUpdateForm beanForm = (EmpJobUpdateForm) form;
		beanForm.setIsAddNew(false);
		
		if(request.getParameter(StringConstants.BTN_EDIT) == null){
			
			int id = CommonUtils.getIntParameter("id", request);
			HreEmpJobs tmp = baseService.getFirstPojo("id", Compare.EQUAL, (long) id, null, null, 0, HreEmpJobs.class);

			if (tmp == null) {
				beanForm.setMessage(StringConstants.BLANK);
				initFormBean(beanForm);
				return mapping.findForward(ACTION_NAME);
			}
			
			beanForm.setId(id);
			beanForm.setEmpNumber(tmp.getEmpNumber());

			beanForm.setJobTitle(tmp.getJobTitleId());
			beanForm.setEmpStatus(CommonUtils.normalizeInteger(tmp.getEmpStatusId()));
			beanForm.setJobCategory(CommonUtils.normalizeInteger(tmp.getJobCategoryId()));
			beanForm.setJoinedDate(CommonUtils.dateToString(tmp.getJoinedDate()));
			beanForm.setSubUnit(CommonUtils.normalizeInteger(tmp.getSubUnitId()));
			beanForm.setLocation(CommonUtils.normalizeInteger(tmp.getLocationId()));
			beanForm.setStartDate(CommonUtils.dateToString(tmp.getContractStartDate()));
			beanForm.setEndDate(CommonUtils.dateToString(tmp.getContractEndDate()));

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);
		
		String message = validateForm(beanForm, false);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			beanForm.setSuccess(false);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		Date startDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getStartDate()));
		Date endDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getEndDate()));
		FormFile myFile = beanForm.getContractFile();

		HreEmpJobs tmp = baseService.getFirstPojo("id", Compare.EQUAL, (long) beanForm.getId(), null, null, 0, HreEmpJobs.class);
		if (tmp == null) {
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		tmp.setJobTitleId(beanForm.getJobTitle());
		tmp.setEmpStatusId(beanForm.getEmpStatus());
		tmp.setJobCategoryId(beanForm.getJobCategory());
		tmp.setJoinedDate(CommonUtils.stringToDate(beanForm.getJoinedDate()));
		tmp.setSubUnitId(beanForm.getSubUnit());
		tmp.setLocationId(beanForm.getLocation());
		tmp.setContractStartDate(startDate);
		tmp.setContractEndDate(endDate);
		
		if (beanForm.getTerminated() == 1) {
			tmp.setTerminatedStatus(true);
			tmp.setTerminationReasonId(beanForm.getTerminationReason());
		}
		
		if(myFile != null && StringUtils.isNotBlank(myFile.getFileName())){

			tmp.setContractFileType(myFile.getContentType());
			tmp.setContractFileSize(myFile.getFileSize());
			tmp.setContractFileName(myFile.getFileName());
			tmp.setContractFileContent(myFile.getFileData());
		}

		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		HreEmployee emp = baseService.getFirstPojo("empNumber", Compare.EQUAL, tmp.getEmpNumber(), null, null, 0, HreEmployee.class);
		emp.setWorkStation(tmp.getSubUnitId());
		emp.setJobTitleCode(beanForm.getJobTitle());
		emp.setEmpStatus(beanForm.getEmpStatus());
		baseService.saveOrUpdate(emp);

		response.getWriter().write(
				 "<script language=\"javascript\">\n" +
						" parent.dw.close();" + 
						 " var param = parent.document.createElement('input'); " +
						 " param.type = 'hidden'; " +
						 " param.name = 'id'; " +
						 " param.value = " + tmp.getEmpNumber() +  ";" +
						 " parent.document.forms[0].appendChild(param);" +
						" parent.document.forms[0].submit(); \n" +
				 "</script>");
		return null;
	}

	private void initFormBean (EmpJobUpdateForm beanForm) {

		List<LabelValueBean> allTerminatedStatuses = new ArrayList<LabelValueBean>();
		allTerminatedStatuses.add(new LabelValueBean("No", "0"));
		allTerminatedStatuses.add(new LabelValueBean("Yes", "1"));

		beanForm.setAllJobTitles(ComboBoxInit.getAllJobTitles(false));
		beanForm.setAllEmpStatuses(ComboBoxInit.getAllEmploymentStatuses(false));
		beanForm.setAllJobCategories(ComboBoxInit.getAllJobCategories(false));
		beanForm.setAllSubUnits(CommonUtils.getSubunits());
		beanForm.setAllLocations(ComboBoxInit.getAllLocations(false));
		beanForm.setAllTerminationReasons(ComboBoxInit.getAllTerminationReasons(false));
		beanForm.setAllTerminatedStatuses(allTerminatedStatuses);
	}
	
	private String validateForm (EmpJobUpdateForm beanForm, boolean isAddNew) {
		
		Date startDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getStartDate()));
		Date endDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getEndDate()));
		
		if (endDate != null) {
			
			if (startDate == null) {
				return "Start date cannot be empty when end date is available!";
			}

			if (!endDate.after(startDate)) {
				return "End date must be after start date!";
			}
		}
		
		if (isAddNew) {

			List<HreEmpJobs> empJobs = baseService.getPojosAnd(new String[]{"empNumber", "terminatedStatus"}, new int[]{Compare.EQUAL, Compare.EQUAL},
					new Object[]{beanForm.getEmpNumber(), false}, null, null, -1, 0, HreEmpJobs.class);
	
			if (empJobs != null && empJobs.size() > 0) {
				return "All of the current jobs must be terminated before adding a new one!";
			}
		}
		
		FormFile myFile = beanForm.getContractFile();
		if(myFile != null && StringUtils.isNotBlank(myFile.getFileName())){
			if(myFile.getFileSize() > 10485760){
				return "Contract file size is too large! (< 10 MB required!)";
			} else if(!"application/pdf".equalsIgnoreCase(myFile.getContentType())
					&& !"application/msword".equalsIgnoreCase(myFile.getContentType())
					&& !"application/vnd.openxmlformats-officedocument.wordprocessingml.document".equalsIgnoreCase(myFile.getContentType())){
				return "Contract file type is not valid! (Only .pdf, .doc or .docx files are accepted!)";
			}
		}

		return StringConstants.BLANK;
	}
}
